
import request from './request'

const LOCAL_KEY = 'zf_current_city_name'

/**
 * 获取当前城市信息
 * @param {Boolean} isReset - 是否重置
 */
const getCurrCity = (isReset) => {
  return new Promise((resolve, reject) => {
    try {
      const localCurrCity = window.localStorage.getItem(LOCAL_KEY)
      if (localCurrCity && !isReset) {
        // 从本地拿
        resolve(JSON.parse(localCurrCity))
      } else {
        // 从百度拿城市在从服务获取城市详细信息
        const bdLocalCity = new window.BMap.LocalCity()
        bdLocalCity.get(async result => {
          const cityName = result.name === '全国' ? '北京' : result.name
          const { data } = await request.get(`/area/info?name=${cityName}`)
          window.localStorage.setItem(LOCAL_KEY, JSON.stringify(data.body))
          resolve(data.body)
        })
      }
    } catch (e) {
      console.log(e)
      reject(new Error('获取定位失败'))
    }
  })
}

export { getCurrCity }